<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input
            v-model="queryParams.permissionName"
            placeholder="请输入权限名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="权限类型" clearable style="width: 200px">
            <el-option label="菜单" value="MENU" />
            <el-option label="按钮" value="BUTTON" />
            <el-option label="接口" value="API" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="权限状态" clearable style="width: 200px">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="Sort"
            class="toolbar-button is-info"
            @click="toggleExpandAll"
          >展开/折叠</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 权限表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="permissionList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="权限名称" prop="permissionName" :show-overflow-tooltip="true" />
        <el-table-column label="权限标识" prop="permissionCode" :show-overflow-tooltip="true" />
        <el-table-column label="权限类型" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="getPermissionTypeTag(scope.row.type)"
              disable-transitions
            >
              {{ getPermissionTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="80" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="primary"
                icon="Plus"
                @click="handleAdd(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >新增</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改权限配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="permissionFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级权限" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="permissionOptions"
                :props="{ value: 'id', label: 'permissionName', children: 'children' }"
                value-key="id"
                placeholder="选择上级权限"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限类型" prop="type">
              <el-select v-model="form.type" placeholder="选择权限类型">
                <el-option label="目录" value="DIRECTORY" />
                <el-option label="菜单" value="MENU" />
                <el-option label="按钮" value="BUTTON" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限名称" prop="permissionName">
              <el-input v-model="form.permissionName" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="权限标识" prop="permissionCode">
              <el-input v-model="form.permissionCode" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.type !== 'BUTTON'">
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.type !== 'BUTTON'">
          <el-col :span="12">
            <el-form-item label="权限图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请输入图标" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio value="0">是</el-radio>
                <el-radio value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="权限状态">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio value="0">显示</el-radio>
                <el-radio value="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissionPage, getPermissionTree, addPermission, updatePermission, deletePermission, updatePermissionStatus } from '@/api/permission'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const isExpandAll = ref(false)
const permissionList = ref([])
const permissionOptions = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref()
const permissionFormRef = ref()

// 查询参数
const queryParams = reactive({
  permissionName: undefined,
  type: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  parentId: 0,
  permissionName: undefined,
  permissionCode: undefined,
  type: 'MENU',
  path: undefined,
  component: undefined,
  icon: undefined,
  sort: 0,
  status: 1,
  visible: '0',
  isFrame: '1',
  remark: undefined
})

// 表单校验规则
const rules = reactive({
  permissionName: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
  permissionCode: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '权限类型不能为空', trigger: 'change' }],
  sort: [{ required: true, message: '权限顺序不能为空', trigger: 'blur' }]
})

// 获取权限列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getPermissionTree()
    if (response.code === 200) {
      permissionList.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限树选项
const getTreeselect = async () => {
  try {
    const response = await getPermissionTree()
    if (response.code === 200) {
      permissionOptions.value = [
        { id: 0, permissionName: '主类目', children: response.data || [] }
      ]
    }
  } catch (error) {
    console.error('获取权限树失败:', error)
  }
}

// 权限类型标签
const getPermissionTypeTag = (type) => {
  const typeMap = {
    'DIRECTORY': 'info',
    'MENU': 'success',
    'BUTTON': 'warning'
  }
  return typeMap[type] || 'info'
}

// 权限类型文本
const getPermissionTypeText = (type) => {
  const typeMap = {
    'DIRECTORY': '目录',
    'MENU': '菜单',
    'BUTTON': '按钮'
  }
  return typeMap[type] || '未知'
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 展开/折叠操作
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}

// 记录上一次状态，避免重复触发
const lastStatusChangeTime = ref(0)

// 权限状态修改
const handleStatusChange = async (row, newVal) => {
  // 检查是否是短时间内重复触发（防止组件初始化时触发）
  const now = Date.now()
  if (now - lastStatusChangeTime.value < 300) {
    return
  }
  lastStatusChangeTime.value = now
  
  const text = row.status === 1 ? '启用' : '停用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.permissionName + '"权限吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updatePermissionStatus({ id: row.id, status: row.status })
    ElMessage.success(text + '成功')
  } catch (error) {
    // 恢复为原来的状态
    row.status = row.status === 0 ? 1 : 0
  }
}

// 新增按钮操作
const handleAdd = (row) => {
  reset()
  getTreeselect()
  if (row && row.id) {
    form.parentId = row.id
  } else {
    form.parentId = 0
  }
  open.value = true
  title.value = '添加权限'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  getTreeselect()
  const permissionId = row.id || ids.value[0]
  Object.assign(form, row)
  open.value = true
  title.value = '修改权限'
}

// 删除按钮操作
const handleDelete = (row) => {
  const permissionIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除权限编号为"' + permissionIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deletePermission(permissionIds[0])
    getList()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    parentId: 0,
    permissionName: undefined,
    permissionCode: undefined,
    type: 'MENU',
    path: undefined,
    component: undefined,
    icon: undefined,
    sort: 0,
    status: 1,
    visible: '0',
    isFrame: '1',
    remark: undefined
  })
  permissionFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交表单
const submitForm = () => {
  permissionFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updatePermission(form)
          ElMessage.success('修改成功')
        } else {
          await addPermission(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
